import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile as AUploadFile } from 'antd';
import { Button, Space, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import type { MB_KEYS } from '../../constants/default';
import { handleSelectFile } from '../../util';
import { TplDownload } from './TplDownload';

import $style from './style.module.scss';

export interface IUploadFileProps {
  readonly?: boolean
  type?: MB_KEYS
  files: AUploadFile[]
  onChange: (files: AUploadFile[]) => void
}

export const UploadFile: React.FC<IUploadFileProps> = ({
  readonly = false,
  type,
  files = [],
  onChange = () => { },
}) => {
  const [fileList, setFileList] = useState<AUploadFile[]>([]);

  useEffect(() => {
    onChange(fileList);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fileList]);

  useEffect(() => {
    setFileList(files);
  }, [files]);

  return (
    <Upload className={$style.upload} multiple disabled={readonly} onPreview={(e) => {
      console.log(e);
    }} openFileDialogOnClick={false} onRemove={(e) => {
      setFileList((state) => {
        const _fileList = state.filter(item => item.uid !== e.uid);
        // formRef.current?.setFieldValue('F_FJ_', JSON.stringify(_fileList));
        return _fileList;
      });
    }}
      fileList={fileList}
      previewFile={async () => { return '#'; }}
    >
      {
        !readonly
          ? (
            <>
              <Space>
                <Button disabled={readonly} icon={<UploadOutlined />} onClick={async () => {
                  const _fileList = await handleSelectFile();
                  console.log(_fileList);
                  const files = [
                    ...fileList,
                    ..._fileList,
                  ];

                  setFileList(files);
                  // formRef.current?.setFieldValue('F_FJ_', JSON.stringify([...fileList]));
                }}>上传文件</Button>
                {
                  !!type && <TplDownload type={type} />
                }
              </Space>
              <br></br>
            </>
            )
          : !fileList.length ? '-' : null
      }
      {/* <Typography.Text disabled>支持 doc,docx、pdf、xls、xlsx、jpg 、png、jpeg 、txt文件格式，最大不超过200M</Typography.Text> */}
    </Upload>
  );
};
